var url2 = document.URL;
var clanServicesBase = 'http://clan.z8games.com/clanServices.asmx/';
var numRibbons = 0;
var hasHonorable = true;

if(url2.indexOf('clan_manage_members') > -1) {
	for(var i=0;i<document.links.length;i++) {
		if(document.links[i].target === "_blank") {
			if(document.links[i].firstChild != null && document.links[i].firstChild.firstChild != undefined) {
				if(document.links[i].firstChild.getAttribute("id").indexOf("requests") > -1) {
					getPlayerInfo(document.links[i].href.substr(document.links[i].href.indexOf("=")+1,document.links[i].href.length), document.links[i]);
				}
			}
		}
	}
}

function getPlayerInfo(usn,row) {
    $.ajax({
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        url: clanServicesBase + 'getPlayerPublicInfo',
        data: '{"usn":' + usn + '}',
        dataType: 'json',
        success: function(msg) {
            var playerinfo2 = $.parseJSON(msg.d);
			chrome.extension.sendRequest({method: "getLocalStorage", key: 'addMembers'}, function(response) {
				if(response.status != "false") {
					var table = row.parentNode.parentNode.parentNode;
					var row2 = table.insertRow(table.rows.length-1);
					var cell2=row2.insertCell(0);
					var KDR = playerinfo2.enemyKillCnt;
					if(playerinfo2.deathCnt > 0) {
						KDR = playerinfo2.enemyKillCnt/playerinfo2.deathCnt;
					}
					cell2.innerHTML="KDR: " + KDR.toFixed(2);
					
					var row3 = table.insertRow(table.rows.length-1);
					var cell3=row3.insertCell(0);
					var WLR = playerinfo2.winCnt;
					if(playerinfo2.deathCnt > 0) {
						WLR = playerinfo2.winCnt/playerinfo2.loseCnt;
					}
					cell3.innerHTML="WLR: " + WLR.toFixed(2);
					
					var row4 = table.insertRow(table.rows.length-1);
					var cell4=row4.insertCell(0);
					cell4.innerHTML="Desertions: " + playerinfo2.escapeCnt;
					
					$.ajax({
						type: 'POST',
						contentType: "application/json; charset=utf-8",
						url: clanServicesBase + 'getPlayerWeapons',
						data: '{"usn":' + usn + '}',
						dataType: 'json',
						success: function(msg) {
							var weapons2 = $.parseJSON(msg.d);
							weaponstr = msg.d;
							var row5 = table.insertRow(table.rows.length-1);
							var cell5=row5.insertCell(0);
							cell5.innerHTML="Unique Weapons: " + weapons2.length;
							
							var xhr2;
							try { xhr2 = new ActiveXObject('Msxml2.XMLHTTP'); }
								catch (e) {
									try { xhr2 = new ActiveXObject('Microsoft.XMLHTTP'); }
									catch (e2) {
										 try { xhr2 = new XMLHttpRequest(); }
										 catch (e3) {
											 xhr2 = false;
										}
									}
								}
								
							xhr2.onreadystatechange = function() {
								if (xhr2.readyState == 4) {
									if (xhr2.status == 200) {
										numRibbons = xhr2.responseText.match(/guide/g).length;
										hasHonorable = xhr2.responseText.match(/Honorable Soldier/g);				
										if(hasHonorable != null) {
											hasHonorable = true;
										} else {
											hasHonorable = false;
										}
									}
									var row6 = table.insertRow(table.rows.length-1);
									var cell6=row6.insertCell(0);
									cell6.innerHTML="Ribbons: " + numRibbons;
										
									var row7 = table.insertRow(table.rows.length-1);
									var cell7=row7.insertCell(0);
									cell7.innerHTML="Honorable Soldier: " + hasHonorable;
								}
							};
							xhr2.open("GET", "http://clan.z8games.com/get_usn_ribbon.aspx?usn=" + usn, true);
							xhr2.send(null);
							
						},
						failure: function(msg) {
							// alert('failed');
						}
					})
				}
			});
        },
        failure: function(msg) {hasHonorable = xhr.responseText.match(/Honorable Soldier/g);
        }
    })
}

var allTitles = document.getElementsByClassName('style2');
var index = 4;
var onForums = false;
if(allTitles.length<4) {//handle mall
	if(allTitles.length>0){
		index = 0;
	} else {
		allTitles = document.getElementsByClassName('toplink');
		onForums = true;
	}
}
if(url2.indexOf('clan_manage_members') > -1) {
	index=3;
}
	var divParent = allTitles[index].parentNode; 
	if(onForums) {
		divParent = divParent.parentNode;
	}
	var events = allTitles[index].cloneNode(true);
	var redeem = allTitles[index].cloneNode(true);
	events.innerText = '';
	events.textContent = '';
	redeem.innerText = '';
	redeem.textContent = '';
	if(index === 0) {
		events.setAttribute('style', 'padding-right:20px;');
		redeem.setAttribute('style', 'padding-right:20px;');
	} else {
		if(onForums) {
			events.setAttribute('style', 'color: #000000; font-size: 11px; padding-right:20px;');
			redeem.setAttribute('style', 'color: #000000; font-size: 11px; padding-right:20px;');
		}
	}
	var eventsChild = document.createElement('a');
	var redeemChild = document.createElement('a');
	eventsChild.innerText = 'Events';
	eventsChild.textContent = 'Events';
	eventsChild.href = 'http://crossfire.z8games.com/events_page.aspx';
	redeemChild.innerText = 'Redeem';
	redeemChild.textContent = 'Redeem';
	redeemChild.href = 'http://crossfire.z8games.com/redeem2.aspx';
	if(allTitles[index].getElementsByClassName('orange2').length>0 ) {
		eventsChild.setAttribute('style', 'font-weight: bold;');
		eventsChild.setAttribute('class', 'orange2');
		events.setAttribute('style', 'padding-right:20px;');
		redeemChild.setAttribute('class', 'orange2');
		redeemChild.setAttribute('style', 'font-weight: bold;');
		redeem.setAttribute('style', 'padding-right:20px;');
	} else {
		if(onForums) {
			eventsChild.setAttribute('class', 'toplink');
			redeemChild.setAttribute('class', 'toplink');
		}
	}
//must remove inside this method otherwise property will not have arrived yet
chrome.extension.sendRequest({method: "getLocalStorage", key: 'events'}, function(response) {
  if(response.status === 'false') {}
  else {
  	events.appendChild(eventsChild);
	divParent.appendChild(events);
	}
});

chrome.extension.sendRequest({method: "getLocalStorage", key: 'redeem'}, function(response) {
  if(response.status === 'false') {}
  else {
  	redeem.appendChild(redeemChild);
	divParent.appendChild(redeem);
  }
});

chrome.extension.sendRequest({method: "getLocalStorage", key: 'home'}, function(response) {
  if(response.status ==='false') {
	var children = divParent.childNodes;
	for(i=0; i<children.length; i++) {
		var children2 = children[i].childNodes;
		for(j=0; j<children2.length; j++) {
			if(children2[j].toString().indexOf("index") > 1) {
				divParent.removeChild(children[i]);
			}
		}
	}
  }
});

chrome.extension.sendRequest({method: "getLocalStorage", key: 'games'}, function(response) {
  if(response.status ==='false') {
	var children = divParent.getElementsByTagName('span');
	for(i=0; i<children.length; i++) {
		if(children[i].firstChild.nodeValue === "Games") {
			divParent.removeChild(children[i]);
		}
	}
  }
});



chrome.extension.sendRequest({method: "getLocalStorage", key: 'download'}, function(response) {
  if(response.status ==='false') {
	var children = divParent.getElementsByTagName('span');
	for(i=0; i<children.length; i++) {
		if(children[i].firstChild.nodeValue === "Download") {
			divParent.removeChild(children[i]);
		}
	}
  }
});

chrome.extension.sendRequest({method: "getLocalStorage", key: 'competitive'}, function(response) {
  if(response.status ==='false') {
	var children = divParent.childNodes;
	for(i=0; i<children.length; i++) {
		var children2 = children[i].childNodes;
		for(j=0; j<children2.length; j++) {
			if(children2[j].toString().indexOf("tournament") > 1) {
				divParent.removeChild(children[i]);
			}
		}
	}
  }
});

var allList;

divParent.parentNode.parentNode.parentNode.setAttribute('style', '100%');
if(document.title.indexOf('Clan Home') > -1) {
	var xhr;
	try { xhr = new ActiveXObject('Msxml2.XMLHTTP'); }
	catch (e) {
		try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
		catch (e2) {
			 try { xhr = new XMLHttpRequest(); }
			 catch (e3) {
				 xhr = false;
			}
		}
	}
		xhr.onreadystatechange = function() {
		if (xhr.readyState == 4) {
			if (xhr.status == 200) {
			//	document.getElementById('div_ribbon').innerHTML = xhr.responseText;
				//use loop to optimize instead of regex
				numRibbons = xhr.responseText.match(/guide/g);
				hasHonorable = xhr.responseText.match(/Honorable Soldier/g);
				if(hasHonorable != null) {
					hasHonorable = true;
				} else {
					hasHonorable = false;
				}
			}
		}
	};

	//xhr.open("GET", "http://clan.z8games.com/get_usn_ribbon.aspx?usn=5084262", true);
//	xhr.send(null);
	
	// var xhr2;
	// try { xhr2 = new ActiveXObject('Msxml2.XMLHTTP'); }
	// catch (e) {
		// try { xhr2 = new ActiveXObject('Microsoft.XMLHTTP'); }
		// catch (e2) {
			 // try { xhr2 = new XMLHttpRequest(); }
			 // catch (e3) {
				 // xhr2 = false;
			// }
		// }
	// }
	
	// xhr2.onreadystatechange = function() {
		// if (xhr2.readyState == 4) {
			// if (xhr2.status == 200) {
				// numRibbons = xhr2.responseText.match(/guide/g);
				// hasHonorable = xhr2.responseText.match(/Honorable Soldier/g);				
				// if(hasHonorable != null) {
					// hasHonorable = true;
				// } else {
					// hasHonorable = false;
				// }
			// }
		// }
	// };
	
	//xhr2.open("GET", "http://clan.z8games.com/clanstat_cf.aspx?guildid=63434", true);
	//xhr2.send("{\"clanid\":\"63434\"}");
}

var SESSIONURL = "";
//Remove forum pagination
chrome.extension.sendRequest({method: "getLocalStorage", key: 'forumPagination'}, function(response) {
	var url = document.URL;
	if(url.indexOf('forum.z8games.com') > -1) {
		if(response.status ==='true') {
		display_post("28792");
		function display_post(A){
			//if(AJAX_Compatible){
			//	vB_PostLoader[A]=new vB_AJAX_PostLoader(A);
			//	vB_PostLoader[A].init()
			//} else{
		//		pc_obj=fetch_object("postcount"+this.postid);//PHP.urlencode(pc_obj.name)
		//		openWindow("showpost.php?"+(SESSIONURL?"s="+SESSIONURL:"")+(pc_obj!=null?"&postcount=100":"")+"&p="+A)
			//}
			return false
		}
		var vB_PostLoader=new Array();
		function vB_AJAX_PostLoader(A){
			this.postid=A;
			this.container=fetch_object("edit"+this.postid)
		}
		vB_AJAX_PostLoader.prototype.init=function(){
			if(this.container){
				postid=this.postid;
				pc_obj=fetch_object("postcount"+this.postid);
				YAHOO.util.Connect.asyncRequest("POST","showpost.php?p="+this.postid,
					{success:this.display,failure:this.handle_ajax_error,timeout:vB_Default_Timeout,scope:this},
					SESSIONURL+"securitytoken="+SECURITYTOKEN+"&ajax=1&postid="+this.postid+(pc_obj!=null?"&postcount="+PHP.urlencode(pc_obj.name):"")
				)
			}
		};
		vB_AJAX_PostLoader.prototype.handle_ajax_error=function(A){
			vBulletin_AJAX_Error_Handler(A)
		};
		vB_AJAX_PostLoader.prototype.display=function(A){
			if(A.responseXML){
				var B=A.responseXML.getElementsByTagName("postbit");
				if(B.length){
					this.container.innerHTML=B[0].firstChild.nodeValue;
					PostBit_Init(fetch_object("post"+this.postid),this.postid)
				}else{
				openWindow("showpost.php?"+(SESSIONURL?"s="+SESSIONURL:"")+(pc_obj!=null?"&postcount="+PHP.urlencode(pc_obj.name):"")+"&p="+this.postid)
				}
			}
		};

		}
	}
});

function fetch_object(A){
	if(document.getElementById){
		return document.getElementById(A)
	}else{
		if(document.all){
			return document.all[A]
		}else{
			if(document.layers){
				return document.layers[A]
			}else{
				return null
			}
		}
	}
}

chrome.extension.sendRequest({method: "getLocalStorage", key: 'clanPage'}, function(response) {
  if(response.status === 'false') {}
  else {
  showMembers();
var ClanDailyMatchInfo;
var memberlist;
var allMembersInfo;// need parse, get from web services
var currentuserinfo;  // use this to determine
var clanid;
var isInternal = 0;
var matchdate;
var matchdatename;
var pagesize = 6;
var urlBase;
urlBase = 'http://z8clan.com/matchsvc.asmx/';

$(function() {  // this going to run when page is ready
    var str = window.location.href.toLowerCase();
    if (str.indexOf('clan.z8games.com.l/') < 0) {  // local?
        urlBase = 'http://clan.z8games.com/matchsvc.asmx/';
        clanServicesBase = 'http://clan.z8games.com/clanServices.asmx/';
    }
	
    clanid = getQueryVariable('guildid'); //'110052';    
    getCurrentLoginInfo();  // to see who is this, whether to show clan points
});


function getClanInfo() {
    $.ajax({
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        url: clanServicesBase + 'getClanPublicInfo',
        data: '{"clanid":' + clanid + '}',
        dataType: 'json',
        success: function(msg) { 
               //alert('get clan info from db');
                var aclaninfo = $.parseJSON(msg.d);
              //  $.cookie("z8_claninfo_" + clanid, msg.d, { expires: 1 });
            
                showClanInfo(aclaninfo);
            // alert(msg.d);
        },
        failure: function(msg) {
            // alert('failed');
        }
    })
}

function showClanInfo(aclaninfo) {
    //alert(aclaninfo.name);
    $('#span_clan_name').html(aclaninfo.name);
    $('#span_clan_rank').html("RANK:" + aclaninfo.clanRank);
    $('#td_leaderlink').html('<a href="charstat_cf.aspx?usn=' + aclaninfo.leaderUsn + '">' + aclaninfo.leaderNick + '</a>');
    $('#td_membercount').html( aclaninfo.MBCount );
    $('#div_clanrank').html(aclaninfo.clanRank);
    var source = "/images/icons/" + getRankDivisionImage(aclaninfo.clanRank);

    $('#img_rankdivision').attr('src', source);
    
    $('#td_clanplaypoints').html(aclaninfo.playPoints);
    $('#td_createddate').html(aclaninfo.regDate);
    $('#td_last_match_date').html(aclaninfo.lastMatchDate);

    var hh = Math.floor( aclaninfo.minutesPlayed / 60);
    $('#td_minutesplayed').html(hh);

    if (aclaninfo.lostMatch > 0) {
        var rr = aclaninfo.wonMatch * 100 / (aclaninfo.lostMatch + aclaninfo.wonMatch);
        rr = rr.toFixed(1)
        $('#td_win_lose_ratio').html(rr + '%');
    }
    

    //if (isInternal == 1) {
        $('#td_matchpoints').html(aclaninfo.matchPoints);
        $('#td_wonmatch').html(aclaninfo.wonMatch);
        $('#td_lostmatch').html(aclaninfo.lostMatch);
   // }
    $('#td_totalclanpoints').html(aclaninfo.matchPoints + aclaninfo.playPoints);
    
    $('#td_enemykill').html(aclaninfo.enemyKill);
    $('#td_death').html(aclaninfo.death);

    $('#td_intro').html(aclaninfo.topic);
    if (aclaninfo.clanMark != '')
        $('#img_clanmark').attr('src', 'http://clan.z8games.com/images/combination/thumnail/' + aclaninfo.clanMark + '.png');    

    var currentuser = $.parseJSON(currentuserinfo);
    if ((currentuser.memberType == '9' || currentuser.memberType == '8') && currentuser.guildid==clanid)
        $('#td_joinrequest').html('<a href="membership_audit.aspx?guildid=' + clanid + '">' + aclaninfo.joinRequest + '</a>');     
    else
        $('#td_joinrequest').html(aclaninfo.joinRequest);

   // if (currentuser.guildid == clanid && aclaninfo.rankDates != '') {  // clan members
        $('#td_clanranking').css('cursor', 'pointer');
        $('#td_clanranking').bind('mouseover', function(e) {
            var xx = e.pageX;
            var yy = e.pageY;
            $('#tbl_clanrankhistory').css({'color':'#ffffff', 'position': 'absolute', 'top': yy, 'left': 500, 'background': 'gray' });
            $('#tbl_clanrankhistory').append('<tr><td>Rank Logs</td><td>Date of Change</td></tr>');
            var arr = aclaninfo.rankDates.split(';');
            //alert(arr.length);
            var arr2;
            for (k = 0; k < arr.length; k++) {
                arr2 = arr[k].split(':');
                $('#tbl_clanrankhistory').append('<tr><td>' + arr2[0] + '</td><td>' + arr2[1] + ' </td></tr>');
            }
            //alert(aclaninfo.rankDates);
            $('#tbl_clanrankhistory').show();
            // alert('showing');
        })

        $('#td_clanranking').bind('mouseout', function(e) {            
            $('#tbl_clanrankhistory tr').remove();
            $('#tbl_clanrankhistory').hide();
            // alert('showing'); 
        }) 
    //}

    if (currentuser.guildid == '0' ) {// no clan
        $('#anchor_apply').attr('href', 'membership_apply.aspx?guildid=' + clanid + '&guildname=' + aclaninfo.name);
    }
    else {
        $('#anchor_apply').hide();
    }
    
}

function getMatches() {
    matchdate = $('#sel_date').val();  //'2011-4-2';

    $("#div_matchlist").html('Loading data...');

    var numericReg = /^\d*[0-9]$/;    
    if (!numericReg.test(clanid)) {
        //alert('Not a valid clan id.');
        return;
     }

     var alist;

     matchdatename = matchdate.replace("-", "_").replace("-", "_");
     $.ajax({
         type: 'POST',
         contentType: "application/json; charset=utf-8",
         url: urlBase + 'getClanMatch',
         data: '{"clanid":"' + clanid + '",matchdate:"' + matchdate + '"}',
         dataType: 'json',
         success: function(msg) {
             var avalue = msg.d;
             alist = $.parseJSON(avalue);
             var total_match = alist.length;
             $("#hd_matchesinfo").val(avalue);

             //  $.cookie("z8_match_" + clanid + "_" + matchdatename, avalue, { expires: 8 });
             //  var ccc = $.cookie("z8_match_" + clanid + "_" + matchdatename);
             //  alert("cookie set:" + ccc);
             bind_1page(1, pagesize);

             var total_page = Math.ceil(total_match / pagesize);
             $('#tr_numbers').empty();
             if (total_page > 20) {
                 $('#tb_numbers').append("<tr id='tr_numbers2'></tr>");
                 $('#tr_numbers2').empty();
             }
             else {
                 $('#tr_numbers2').empty();
             }
             
             if (total_page > 1) {  // if 1 no show
                 var container;
                 for (i = 1; i <= total_page; i++) {
                     if (i < 21)
                         container = $('#tr_numbers');
                     else
                         container = $('#tr_numbers2');

                     container.append("<td id=pager" + i + " style='width:15px;cursor:pointer' onclick='bind_1page(" + i + "," + pagesize + "," + total_page + ");'>" + i + "</td>");
                 }
             }
         },
         failure: function(msg) {
             //alert('failed');
         }
     })
    
}



function bind_1page(pageno,pagesize, pagetotal) {
    var list = new Array();
    list.length = 0;
    var anumber;
    var total_match;
    //var matchcookie = $.cookie("z8_match_" + clanid + "_" + matchdatename);
    var matchinfo = $("#hd_matchesinfo").val();
    matchlist = $.parseJSON(matchinfo);
    
    total_match = matchlist.length;
     
    var xx = 0, nn;
    var astr;
    for (i=0; i<pagesize; i++)
    {
        nn = (pageno - 1) * pagesize + i;
        if (total_match > nn )   // how many in this page
        {
            xx++;
            list.length = xx;
            list[i] = matchlist[(pageno - 1) * pagesize + i];
            //list[i].map =  interpretMap(list[i].map);
            astr = interpretMap(list[i].map);
            list[i].mapName = getMapName(astr);
            list[i].matchType = getMatchType(astr);
            
            list[i].myClanDivisionName = getRankDivisionName(list[i].myClanRank);
            list[i].rivalClanDivisionName = getRankDivisionName(list[i].rivalClanRank);

           // alert(list[i].rivalClanDivisionName);
            list[i].rivalClanWinWidth = "display:none";
            list[i].myClanWinWidth = "display:none"; 
           
             list[i].finalScore = 'Final Score';
            if  (  list[i].myClanPoints == '0' && list[i].rivalClanPoints == '0')//  tie, if tied match, not show Win image
            {
                 list[i].finalScore = 'First Half';
            }
            else
            {
                if (list[i].myClanWin == '1') {
                    list[i].myClanWinWidth = "display:yes";  //"yes";
                    list[i].rivalClanWinWidth = "display:none";
                }
                else {
                    list[i].myClanWinWidth = "display:none";
                    list[i].rivalClanWinWidth = "display:yes";
                } 
            }
          
            
            if (list[i].myClanMark == '')
                list[i].myClanMark = 'http://clan.z8games.com/images/mark/clanminilogo.jpg';
            else
                list[i].myClanMark = 'http://clan.z8games.com/images/combination/thumnail/' + list[i].myClanMark + '.png';
            

            if (list[i].rivalClanMark == '')
                list[i].rivalClanMark = 'http://clan.z8games.com/images/mark/clanminilogo.jpg';
            else
                list[i].rivalClanMark = 'http://clan.z8games.com/images/combination/thumnail/' + list[i].rivalClanMark + '.png';
            
            if (list[i].round == 0)
                list[i].round = "N/A";
        }     
    }

    for (i = 1; i <= pagetotal; i++) {
        $('#pager' + i).css({ 'color': 'white' });
    }

    $('#pager' + pageno).css({ 'color': 'red' });

    $("#div_matchlist").empty();
    if (list.length == 0) {
        $('#div_matchlist').html('<font color="white"><img src="/images/bg/no_matches_img.jpg" /></font>');
        return;
    }
    $("#matches_template").template("matches");
    $.tmpl("matches", list).appendTo("#div_matchlist");
 
    for (ix = 0; ix < list.length; ix++) {
        var srl = list[ix].gameLogSRL;
       // alert(55);
        getMatchDetails(srl);  
    }
}



function bindDetails(gameLogSrl, detailslist) {
    var myPlayerList = new Array();
    var rivalPlayerList = new Array();
    var ii_my = 0;
    var ii_rival = 0;
    var awards;
    for (i = 0; i < detailslist.length; i++) {
        awards = "";
        if (detailslist[i].headShotKill >= 5)
            awards = awards + "<img title='Headshot(5+)' src='/images/icons/hs.png'>"; 

        if (detailslist[i].friendKill >= 1)
            awards = awards + "<img title='Friendly Kills(1+)' src='/images/icons/fk.png'>";          

        if (detailslist[i].survivalRound >= 4)
            awards = awards + "<img title='Rounds Survived(4+)' src='/images/icons/survival.png'>"; 
            
        if (detailslist[i].totalKill >= 10)
            awards = awards + "<img title='Kills for Match(10+)' src='/images/icons/kills.png'>";
            
        if (detailslist[i].death >= 20)
            awards = awards + "<img title='Deaths for Match(20+)' src='/images/icons/deaths.png'>";

        if (detailslist[i].escape >= 4)
            awards = awards + "<img title='Escapes into Portal(4+)' src='/images/icons/escaped.png'>";

        detailslist[i].awards = awards;  // add a property     
            
        if (detailslist[i].guildID == clanid)  // my clan players
        {
            myPlayerList[ii_my] = detailslist[i]; 
            ii_my ++;
        }
        else
        {
            rivalPlayerList[ii_rival] = detailslist[i];            
            rivalPlayerList[ii_rival].awards = rivalPlayerList[ii_rival].awards + "&nbsp;&nbsp;"
            ii_rival ++;
        }
    }
    // alert(myPlayerList[0].nick);
    var tt;
    for (i = 1; i <= ii_my; i++) {
        tt = i - 1;
        $('#' + gameLogSrl + '_my_nick' + i).html("<a target='_blank' href='http://clan.z8games.com/charstat_cf.aspx?usn=" + myPlayerList[tt].usn + "'>" + myPlayerList[tt].nick + "</a>");
        $('#' + gameLogSrl + '_my_rewards' + i).html(myPlayerList[tt].awards);
        $('#' + gameLogSrl + '_my_killdeath' + i).html(myPlayerList[tt].totalKill + '/' + myPlayerList[tt].death); 
    }

    var ll;
    for (i = 1; i <= ii_rival; i++) {
        tt = i - 1;
        ll = 12 -  rivalPlayerList[tt].nick.length ;
        for (ii=0; ii<ll;ii++) { 
            rivalPlayerList[tt].nick = rivalPlayerList[tt].nick + "&nbsp;";
        }
        
        $('#' + gameLogSrl + '_rival_nick' + i).html("<a target='_blank' href='http://clan.z8games.com/charstat_cf.aspx?usn=" + rivalPlayerList[tt].usn + "'>" + rivalPlayerList[tt].nick + "</a>");
        $('#' + gameLogSrl + '_rival_rewards' + i).html(rivalPlayerList[tt].awards);
        $('#' + gameLogSrl + '_rival_killdeath' + i).html(rivalPlayerList[tt].totalKill + '/' + rivalPlayerList[tt].death);
    }
 
}

function getMatchDetails(gameLogSrl) {
//    if ($.cookie("z8_match_" + gameLogSrl)) {
//        var avalue = $.cookie("z8_match_" + gameLogSrl);
//        alert("match details cookie used:" + gameLogSrl + "///" + avalue);
//        $('#hd_detailsinfo').val(avalue);
//        var alist = $.parseJSON(avalue);
//        bindDetails(gameLogSrl, alist);
//        return;
//    }
    $.ajax({
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        url: urlBase + 'getClanMatchDetails',
        data: '{"gameLogSrl":"' + gameLogSrl + '"}',
        dataType: 'json',
        success: function(msg) {
            $('#hd_detailsinfo').val(msg.d);

         //   $.cookie("z8_match_" + gameLogSrl, msg.d, { expires: 8 });
         //   alert("match details cookie set:" + gameLogSrl + "///" + msg.d);
            var alist = $.parseJSON(msg.d);
            bindDetails(gameLogSrl, alist);
            // alert(msg.d);

        },
        failure: function(msg) {
            //alert('failed');
        }
    })

    
}

function isLoggedIn() {
    $.ajax({
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        url: urlBase + 'isLoggedIn',
        dataType: 'json',
        success: function(msg) {
            var alist = $.parseJSON(msg.d);
            var result = alist.result;
        },
        failure: function(msg) {
            //alert('failed');
        }
    })
}

function isInternalIP() {  // will run when user change the date with select , now out side user cant see that select
    $.ajax({
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        url: urlBase + 'isInternalIP',
        dataType: 'json',
        success: function(msg) {
            var ret = $.parseJSON(msg.d);
            var result = ret.result;
            //result = 'Yes';
            if (result == 'Yes')  // only open to internal
            {
                $('#tbl_all').show();
                isInternal = 1;
               // getMatches();
            }
            else {
                $('#tbl_all').hide();
            } 

        },
        failure: function(msg) {
            //alert('failed');
        }
    })
}

function showYesterdayMatch() {
    var adate = getDateString(-1);
    $('#sel_date').val(adate);
    getMatches();
}

function getDateString(minusDays) {
    var d = new Date();
    if (urlBase == 'http://z8clan.com/matchsvc.asmx/') {
        d = new Date(2011,3,5);
    }
    
    var yyyy = d.getFullYear();
    var mm = d.getMonth();
    var dd = d.getDate();
    var newdate = dd + minusDays;
    var newd = new Date(yyyy, mm, newdate);


    yyyy = newd.getFullYear();
    mm = newd.getMonth();
    dd = newd.getDate();
    mm = mm + 1;

    return yyyy + '-' + mm + '-' + dd;    
}

function interpretMap(code) { 
    switch(code)
    {
    case '0':    return	'EagleEye(S&D)';
    case '1':    return	'Mexico(S&D)';
    case '2':    return	'Ceyhan(S&D)';
    case '3':    return	'Ship(TD)';
    case '4':    return	'Mexico(TD)';
    case '5':    return	'Train(TD)';
    case '6':    return	'Laboratory(GM)';
    case '7':    return	'Sub Base(S&D)';
    case '8':    return	'Monaco(TD)';
    case '9':    return	'Colombia(EM)';
    case '10':    return 'BlackWidow(FFA)';
    case '11':    return	'LostRelics(GM)';
    case '12':    return	'Port(FFA)';
    case '14':    return	'Factory(TD)';
    case '15':    return	'PowerPlant(TD)';
    case '16':    return	'Factory(S&D)';
    case '17':    return	'Hakenkreuz(GM)';
    case '19':    return	'CrossRoad(EM)';
    case '20':    return	'Egypt(TD)';
    case '21':    return	'Port(S&D)';
    case '22':    return	'BlackWidow(S&D)';
    case '23':    return	'The Mine(S&D)';
    case '24':    return	'Arena(TD)';
    case '25':      return 'Complex(GM)';
    case '26':      return 'Halloween(EM)';
    case '27':    return	'Temple Ruins(ESC)';
    case '28':    return	'DesertStorm(S&D)';
    case '29':    return	'Command Ops(ESC)';
    case '30':    return	'Santoria(S&D)';
    case '31':    return	'Forbidden Palace(TD)';
    case '32':    return	'Prison(EM)';
    case '33':    return	'Castle(S&D)';
    case '34':    return	'Alaska(EM)';
    case '35':    return	'Metro(GM)';
    case '36':    return	'Arena(WO)';
    case '37':    return	'Fortress(TD)';
    case '38':    return	'Downtown(S&D)';
    case '39':    return	'Prison(TD)';
    case '40':    return	'Christmas(EM)';
    case '41':    return	'13 Zone(MM)';
    case '42':    return	'port(MM)';
    case '43':    return	'Excavation(MM)';
    case '44':    return	'Re. Facility(MM)';
    case '45':    return	'Tranquility(MM)';
    case '46':    return	'Arena2(WO)';
    case '47':    return	'Cagoship(ESC)';
    case '48':    return	'Stronghold(MM)';
    case '50':    return	'Cairo(TD)';
    case '51':    return	'13 Zone(HM)';
    case '52':    return	'port(HM)';
    case '53':    return	'Excavation(HM)';
    case '54':    return	'Re. Facility(HM)';
    case '55':    return	'Tranquility(HM)';
    case '56':    return	'Stronghold(HM)';
    case '57':    return	'Merida(HM)';
    case '58':    return	'Mall(MM)';
    case '59':    return	'Mall(HM)';
    case '61': return 'Sewers(TD)';   
    case '62': return 'Dry World(EM)';
    case '63': return 'Compound(S&D)';
    case '64': return 'China Town(TD)';
    case '65': return 'N/A';
    case '66': return 'N/A';
    case '67': return 'Ankara(S&D)';
    case '68': return 'Orbital Station(TDM)';
    case '69': return 'Venice(ZM) ';
    case '70': return 'Bio Facility(GM)';
    case '71': return 'Mansion(HMX) ';
    case '72': return 'Dark Village(HMX)';
    case '73': return 'Zone 13(HMX) ';
    case '74': return 'port(HMX)';
    case '75': return 'Excavation(HMX)';
    case '76': return 'Re. Facility(HMX)';
    case '77': return 'Tranquility(HMX)';
    case '78': return 'Stronghold(HMX)';
    case '79': return 'Terminal(EM) ';
    case '80': return 'Eagle Eye(FFA)';
 }
 return code;
 
}

function getMapName(Name_Type) {
    var str = Name_Type.toString();
    var i = str.indexOf('(');
    if (i<0)
        return str;
    
    var mapname = str.substring(0, i);

    return mapname;
}

function getMatchType(Name_Type) {
    var str = Name_Type.toString();
    var i = str.indexOf('(');
    if (i < 0)
        return str;
        
    i++;
    var j = str.indexOf(')');
    var matchtype = str.substring(i, j);

    return matchtype;
}

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0].toLowerCase() == variable.toLowerCase()) {
            return pair[1];
        }
    }
}

function showMembers() { // include lieutenants part now
    var numericReg = /^\d*[0-9]$/;     
    if (!numericReg.test(clanid)) {
        //alert('Not a valid clan id.');
        return;
    }
    $.ajax({
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        url: clanServicesBase + 'getClanMembers',  // will return all members include lieutenants and clan leader
        data: '{"clanid":"' + clanid + '"}',
        dataType: 'json',
        success: function(msg) {
            //alert(msg.d);
            //memberlist = $.parseJSON(msg.d);
            //$("#hd_membersinfo").val(msg.d);

            allMembersInfo = msg.d;

            memberlist = $.parseJSON(allMembersInfo);
            if (memberlist == undefined)
                return;
	    allList = memberlist;
            var normallist = filterMembers(memberlist, '0');  // get normal members

            var total_members = normallist.length;
			
			chrome.extension.sendRequest({method: "getLocalStorage", key: 'clanPagination'}, function(response) {
				if(response.status === 'false') {
            var memberpagesize = 10;
            var total_MemberPage = Math.ceil(total_members / memberpagesize);
            bind_1pageMembers(1, memberpagesize, total_MemberPage);  //1 is first page, 10 is pagesize
            $('#tr_pagelinks').empty();

            if (total_MemberPage > 1) {  // if 1 no show
                for (i = 1; i <= total_MemberPage; i++) {
                    $('#tr_pagelinks').append("<td id=memberpager" + i + " style='width:15px;cursor:pointer' onclick='bind_1pageMembers(" + i + "," + memberpagesize + "," + total_MemberPage + ");'>" + i + "</td>");
                }
            }
            $('#tr_pagelinks').append("<td style='width:215px;'></td>");  // add one more column to hold place

            //next bind lieutenants list
            var lieutenantlist = filterMembers(memberlist, '8');  // get lieutenant members
            var total_lieutenants = lieutenantlist.length;
            var lieutenantpagesize = 5;
            var total_lieutenantPage = Math.ceil(total_lieutenants / lieutenantpagesize);
            //alert(total_members + "//" + total_MemberPage);
            chrome.extension.sendRequest({method: "getLocalStorage", key: 'clanPoints'}, function(response) {
				bind_1pageLieutenants(1, lieutenantpagesize, total_lieutenantPage, response.status);  //1 is first page, 10 is pagesize
			});
            $('#tr_lieutenantPager').empty(); // pager links

            if (total_lieutenantPage > 1) {  // if 1 no show
                for (i = 1; i <= total_lieutenantPage; i++) {
                    $('#tr_lieutenantPager').append("<td  id=lietenantpager" + i + " style='width:15px;cursor:pointer' onclick='bind_1pageLieutenants(" + i + "," + lieutenantpagesize + "," + total_lieutenantPage + ");'>" + i + "</td>");
                }
            }
            $('#tr_lieutenantPager').append("<td style='width:215px;'></td>");

			} else {
            var memberpagesize = 99;
            var total_MemberPage = Math.ceil(total_members / memberpagesize);
            bind_1pageMembers(1, memberpagesize, total_MemberPage);  //1 is first page, 10 is pagesize
            $('#tr_pagelinks').empty();

            if (total_MemberPage > 1) {  // if 1 no show
                for (i = 1; i <= total_MemberPage; i++) {
                    $('#tr_pagelinks').append("<td id=memberpager" + i + " style='width:15px;cursor:pointer' onclick='bind_1pageMembers(" + i + "," + memberpagesize + "," + total_MemberPage + ");'>" + i + "</td>");
                }
            }
            $('#tr_pagelinks').append("<td style='width:215px;'></td>");  // add one more column to hold place

            //next bind lieutenants list
            var lieutenantlist = filterMembers(memberlist, '8');  // get lieutenant members
            var total_lieutenants = lieutenantlist.length;
            var lieutenantpagesize = 99;
            var total_lieutenantPage = Math.ceil(total_lieutenants / lieutenantpagesize);
			chrome.extension.sendRequest({method: "getLocalStorage", key: 'clanPoints'}, function(response) {
				bind_1pageLieutenants(1, lieutenantpagesize, total_lieutenantPage, response.status);  //1 is first page, 10 is pagesize
			});
                   $('#tr_lieutenantPager').empty(); // pager links

            if (total_lieutenantPage > 1) {  // if 1 no show
                for (i = 1; i <= total_lieutenantPage; i++) {
                    $('#tr_lieutenantPager').append("<td  id=lietenantpager" + i + " style='width:15px;cursor:pointer' onclick='bind_1pageLieutenants(" + i + "," + lieutenantpagesize + "," + total_lieutenantPage + ");'>" + i + "</td>");
                }
            }
            $('#tr_lieutenantPager').append("<td style='width:215px;'></td>");

			}	
			
			});
            // next show leader info

            var leaderlist = filterMembers(memberlist, '9');  // get lieutenant members

            $('#td_leader').html("<a href='charstat_cf.aspx?usn=" + leaderlist[0].usn + "'>" + leaderlist[0].nick + "</a>");
            var rank = parseInt(leaderlist[0].lev) + 1;
            $('#img_leader').attr('src', "/images/rankingicon/class_" + rank + ".jpg");
            var currentuser = $.parseJSON(currentuserinfo);
			chrome.extension.sendRequest({method: "getLocalStorage", key: 'clanPoints'}, function(response) {
				if(response.status !== "false") {
					$('#td_leader_points').html("Points:&nbsp;&nbsp;" + leaderlist[0].clan_points);
				 }
			});
	    	 // this going to run when page is ready
	    var str = window.location.href.toLowerCase();
	    if (str.indexOf('z8clan.com/') < 0) {  // local? 
		clanServicesBase = 'http://clan.z8games.com/clanServices.asmx/';
	    }
	    usn = leaderlist[0].usn;
	
	    getLeaderInfo();
	    // getPlayerWeapons(); 
	},
        failure: function(msg) {
            //alert('failed');
        }
    })

}

function bind_1pageMembers(pageno, pagesize, pagetotal) { 
    for (i = 1; i <= pagetotal; i++) {
        $('#memberpager' + i).css({ 'color': 'white' });
    }

    $('#memberpager' + pageno).css({ 'color': 'red' });
    $('#memberpager').append("sadasd");

    $("#div_memberlist").empty();

    var str = allMembersInfo;  // $("#hd_membersinfo").val();
    //alert(str);
    memberlist = $.parseJSON(str);
    var list = new Array();
    list.length = 0;

    var normallist = filterMembers(memberlist,'0');  // get normal members
    var totalmembers = normallist.length;
    var start = pagesize * (pageno -1)
    var cnt = 0; 
    var currentuser = $.parseJSON(currentuserinfo);

    while (cnt < pagesize && start < totalmembers) {
        list[cnt] = normallist[start];
        list[cnt].action = '';
        if (list[cnt].usn == currentuser.usn) {
            list[cnt].action = 'Leave';
	 } else {

	 }

        if (clanid == currentuser.guildid && (currentuser.memberType == '9' || currentuser.memberType == '8'))
            list[cnt].action = 'Kick';         
        
        cnt++;
        start++;
    }

    $("#clan_members_template").template("members_templ");
    $.tmpl("members_templ", list).appendTo("#div_memberlist");
    for(var k = 0; k < list.length; k++) {
    	usn = list[k].usn;
	if(list[k].memberType == 0){
		getPlayerInfo(k);
	} else {
		getLieutInfo(k);
	}
	
   }


}

function bind_1pageLieutenants(pageno, pagesize, pagetotal, addPoints) {
    for (i = 1; i <= pagetotal; i++) {
        $('#lietenantpager' + i).css({ 'color': 'white' });
    }

    $('#lietenantpager' + pageno).css({ 'color': 'red' });

    $("#div_lieutenantlist").empty(); 
 
    memberlist = $.parseJSON(allMembersInfo);  //$.parseJSON(str);   

    var lieutenantlist = filterMembers(memberlist, '8');  // get normal members
    var totalmembers = lieutenantlist.length;
    var start = pagesize * (pageno - 1)
    var cnt = 0; 
    var currentuser = $.parseJSON(currentuserinfo);
    var list = new Array();
    list.length = 0;
    
    while (cnt < pagesize && start < totalmembers) {
        list[cnt] = lieutenantlist[start];
        list[cnt].action = '';

        if (currentuser.memberType == '9' && clanid == currentuser.guildid) {
            list[cnt].clan_points = "Points:&nbsp;&nbsp;" + list[cnt].clan_points;
            list[cnt].action = 'Kick';
        }
        else if (list[cnt].usn == currentuser.usn) {
		list[cnt].action = 'Leave';
	   
            }
		if(addPoints === "false") {
			list[cnt].clan_points = '';
		} else {
			list[cnt].clan_points = "Points:&nbsp;&nbsp;" + list[cnt].clan_points;
		}
        cnt++;
        start++;
    }

    $("#clan_lieutenants_template").template("lieutenants_templ");
    $.tmpl("lieutenants_templ", list).appendTo("#div_lieutenantlist");
    
   for(var k = 0; k < list.length; k++) {
    	usn = list[k].usn;
		getLieutInfo(k);
    }

}

function filterMembers(totalMembers,memberType) {// admin value
    var list = new Array();
    list.length = 0;
    var cnt = 0;
    if (totalMembers == undefined)
        return list;
    
    var total = totalMembers.length;
    for (i = 0; i < total; i++) {
        if (totalMembers[i].memberType == memberType) { 
            list[cnt++] = totalMembers[i];
        }
    }
    return list;
}

function getRankDivisionImage(rank) {
    if (rank <= 0)
        return "R20001.jpg";
    else if (rank < 50)
        return "R50.jpg";
    else if (rank < 100)
        return "R100.jpg";
    else if (rank < 250)
        return "R250.jpg";
    else if (rank < 500)
        return "R500.jpg";
    else if (rank < 1000)
        return "R1000.jpg";
    else if (rank < 2000)
        return "R2000.jpg";
    else if (rank < 4000)
        return "R4000.jpg";
    else if (rank < 7000)
        return "R7000.jpg";
    else if (rank < 10000)
        return "R10000.jpg";
    else if (rank < 12000)
        return "R12000.jpg";
    else if (rank < 14000)
        return "R14000.jpg";
    else if (rank < 17000)
        return "R17000.jpg";
    else if (rank < 20000)
        return "R20000.jpg";
    else
        return "R20001.jpg";   
}

function getRankDivisionName(rank) {
    if (rank < 50)
        return "MASTER";
    else if (rank < 101)
        return "ELITE";
    else if (rank < 251)
        return "DIAMOND A";
    else if (rank < 501)
        return "DIAMOND B";
    else if (rank < 1001)
        return "DIAMOND C";
    else if (rank < 2001)
        return "GOLD A";
    else if (rank < 4001)
        return "GOLD B";
    else if (rank < 7001)
        return "GOLD C";
    else if (rank < 10001)
        return "SILVER A";
    else if (rank < 12001)
        return "SILVER B";
    else if (rank < 14001)
        return "SILVER C";
    else if (rank < 17001)
        return "BRONZE A";
    else if (rank < 20001)
        return "BRONZE B";
    else
        return "BRONZE C";
}

function getCurrentLoginInfo() {
    var numericReg = /^\d*[0-9]$/;
    if (!numericReg.test(clanid)) {
        //alert('Not a valid clan id.');
        return;
    }
    $.ajax({
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        url: clanServicesBase + 'getCurrentLoginIDInfo',
        // data: '{"clanid":"' + clanid + '"}',
        dataType: 'json',
        success: function(msg) {
           // alert(msg.d);
            currentuserinfo = msg.d; //$.parseJSON(msg.d);
            // alert(msg.d);

            getClanInfo();  // get and show clan info
			  // chrome.extension.sendRequest({method: "getLocalStorage", key: 'clanPoints'}, function(response) {
		//	if(response.status === "true") {
            showMembers(); // show members after current user data is ready
			//	}
		//});
          //   alert(info.usn);
        },
        failure: function(msg) {
            //alert('failed');
        }
    })

}


var usn;
var weaponstr;
var playerstr;
var pagesize = 10;
var urlBase;
var clanServicesBase;
urlBase = 'http://z8clan.com/matchsvc.asmx/';
clanServicesBase = 'http://z8clan.com/clanServices.asmx/';

function getLeaderInfo() {
    $.ajax({
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        url: clanServicesBase + 'getPlayerPublicInfo',
        data: '{"usn":' + usn + '}',
        dataType: 'json',
        success: function(msg) {
           // alert('get info from db');
            var playerinfo2 = $.parseJSON(msg.d);
          //  $.cookie("z8_player_" + usn, msg.d, { expires: 1 });
			chrome.extension.sendRequest({method: "getLocalStorage", key: 'clanDate'}, function(response) {
				showLeaderInfo(playerinfo2, response.status);
				// alert(msg.d);
			});
        },
        failure: function(msg) {
            // alert('failed');
        }
    })
}

function getPlayerInfo(index) {
console.log('next');
    $.ajax({
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        url: clanServicesBase + 'getPlayerPublicInfo',
        data: '{"usn":' + usn + '}',
        dataType: 'json',
        success: function(msg) {
            var playerinfo2 = $.parseJSON(msg.d);

			chrome.extension.sendRequest({method: "getLocalStorage", key: 'clanDate'}, function(response) {
				showPlayerInfo(playerinfo2, index, response.status);
			});
        },
        failure: function(msg) {
            // alert('failed');
        }
    })
}

function getLieutInfo(index) {
    $.ajax({
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        url: clanServicesBase + 'getPlayerPublicInfo',
        data: '{"usn":' + usn + '}',
        dataType: 'json',
        success: function(msg) {
           // alert('get info from db');
            var playerinfo2 = $.parseJSON(msg.d);
          //  $.cookie("z8_player_" + usn, msg.d, { expires: 1 });
		  	chrome.extension.sendRequest({method: "getLocalStorage", key: 'clanDate'}, function(response) {
				showLieutInfo(playerinfo2, index, response.status);
			});
            // alert(msg.d);
        },
        failure: function(msg) {
            // alert('failed');
        }
    })
}
function showPlayerInfo(playerinfo, index, format) {
	var adate = playerinfo.lastPlayDate.substring(2);
		if(format !== 'false') {
			if(format === "yy-mm-dd") {
			} else if(format === "dd-mm-yy") {
					var n = adate.split("-");
					adate = n[2] + '-' + n[1] + '-' + n[0];
			}
		} else {// is false
			adate = '';
		}
	
	$('#div_memberlist')[0].childNodes[index].rows[1].insertCell(2).innerHTML = adate;
}

function showLieutInfo(playerinfo, index, format) {
	var adate = playerinfo.lastPlayDate.substring(2);
		if(format !== 'false') {
			if(format === "yy-mm-dd") {
			} else if(format === "dd-mm-yy") {
					var n = adate.split("-");
					adate = n[2] + '-' + n[1] + '-' + n[0];
			}
		} else {// is false
			adate = '';
		}
	
	$('#div_lieutenantlist')[0].childNodes[index].rows[1].insertCell(2).innerHTML = adate;
}

function showLeaderInfo(playerinfo, format) {
	var adate = playerinfo.lastPlayDate.substring(2);
		if(format !== 'false') {
			if(format === "yy-mm-dd") {
			} else if(format === "dd-mm-yy") {
					var n = adate.split("-");
					adate = n[2] + '-' + n[1] + '-' + n[0];
			}
		} else {// is false
			adate = '';
		}
   document.getElementById("img_leader").parentNode.parentNode.insertCell(2).innerHTML = adate; 
}

function getPlayerWeapons() {
    $.ajax({
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        url: clanServicesBase + 'getPlayerWeapons',
        data: '{"usn":' + usn + '}',
        dataType: 'json',
        success: function(msg) {
            //alert('get info from db');
            var weapons2 = $.parseJSON(msg.d);
            weaponstr = msg.d;
           // $.cookie("z8_weapon_" + usn, msg.d, { expires: 1 });

            showPlayerWeapons(weapons2);
            // alert(msg.d);
        },
        failure: function(msg) {
            // alert('failed');
        }
    })
}

function showPlayerWeapons(weaponlist)
{
bind_1page(1, pagesize);
var len = weaponlist.length;
var total_page = Math.ceil(len / pagesize);
$('#tr_numbers').empty();
//alert(total_page);
if (total_page > 1) {  // if 1 no show
    var container;
    container = $('#tr_numbers');  
    for (i = 1; i <= total_page; i++) { 
        container.append("<td id=pager" + i + " style='width:15px;cursor:pointer' onclick='bind_1page(" + i + "," + pagesize + "," + total_page + ");'>" + i + "</td>");
    }// page loop
    }// more than 1              
}// fn end



function bind_1page(pageno, pagesize, pagetotal) {
    var list = new Array();
    list.length = 0;
    var anumber;
    var total_match;
 
    weaponlist = $.parseJSON(weaponstr);

    total_weapon = weaponlist.length;

    var xx = 0, nn;
    var astr;
    for (i = 0; i < pagesize; i++) {
        nn = (pageno - 1) * pagesize + i;
        if (total_weapon > nn)   // how many in this page
        {
            xx++;
            list.length = xx;
            list[i] = weaponlist[(pageno - 1) * pagesize + i];  
        }
    }

    for (i = 1; i <= pagetotal; i++) {
        $('#pager' + i).css({ 'color': 'white' });
    }

    $('#pager' + pageno).css({ 'color': 'red' });

    $("#div_weaponlist").empty();
    if (list.length == 0) {
        $('#div_weaponlist').html('<font color="white">No weapons.</font>');
        return;
    }
    $("#weapon_template").template("weapons");
    $.tmpl("weapons", list).appendTo("#div_weaponlist");

}

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0].toLowerCase() == variable.toLowerCase()) {
            return pair[1];
        }
    }
}

	}
});
var z8Gamesurl = ".z8games.com";
var sessionid = "NET_SessionId";

Cookies.init();


function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

//
//console.log(document.cookie);
//console.log(readCookie(z8Gamesurl));
//chrome.cookies.get({"url": z8Gamesurl,"name": sessionid}, function(cookie) {console.log("success");});

chrome.extension.sendRequest({method: "getLocalStorage", key: 'community'}, function(response) {
	var url = document.URL;
	if(url.indexOf('forum.z8games.com') > -1) {
		if(response.status ==='true') {			
			var header = getElementsByClassName(document,'header_bg');
			header[0].parentNode.getElementsByTagName('table')[4].rows[0].deleteCell(2);
		}
	}
});

chrome.extension.sendRequest({method: "getLocalStorage", key: 'calendar'}, function(response) {
	var url = document.URL;
	if(url.indexOf('forum.z8games.com') > -1) {
		if(response.status ==='true') {			
			var header = getElementsByClassName(document,'header_bg');
			var index = 3;
			var row = header[0].parentNode.getElementsByTagName('table')[4].rows[0];
			if(row.cells.length != 8) {
				index = 2;//if community was deleted
			}
			row.deleteCell(index);
		}
	}
});

chrome.extension.sendRequest({method: "getLocalStorage", key: 'imageSize'}, function(response) {
	var url = document.URL;
	if(url.indexOf('forum.z8games.com') > -1) {
		if(response.status !== undefined) {			
			var z = document.getElementsByTagName('img');
			for(i=0;i<z.length;i++) {
			if(z[i].width >= response.status){
				z[i].width = response.status;
				}
			}
		}
	}
});

chrome.extension.sendRequest({method: "getLocalStorage", key: 'defaultFont'}, function(response) {
	var url = document.URL;
	if(url.indexOf('forum.z8games.com') > -1) {
		if(response.status === 'true') {
			var font_tags=document.getElementsByTagName("font");
			for(var i=0; i<font_tags.length; i++) {
			  font_tags[i].face = null;
			  font_tags[i].size = null;
			  font_tags[i].color = null;
			}
		}
	}
});


function getElementsByClassName(node,classname) {
  if (node.getElementsByClassName) { // use native implementation if available
    return node.getElementsByClassName(classname);
  } else {
    return (function getElementsByClass(searchClass,node) {
        if ( node == null )
          node = document;
        var classElements = [],
            els = node.getElementsByTagName("*"),
            elsLen = els.length,
            pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"), i, j;

        for (i = 0, j = 0; i < elsLen; i++) {
          if ( pattern.test(els[i].className) ) {
              classElements[j] = els[i];
              j++;
          }
        }
        return classElements;
    })(classname, node);
  }
}
